'use strict'

const { Controller } = require('egg')

class AdminController extends Controller {
  /**
   * @api {post} /login [登录]
   * @apiGroup Account
   * @apiBody {String} username 用户名称
   * @apiBody {String} password  用户密码
   *
   * @apiSuccessExample {json} Success-Response:
    {
        "code": 0,
        "msg": "登录成功",
        "data": {
          "username": "llz", // 用户名称
          "isAdmin": true, // 超级管理员，拥有所有权限
          "token": "token", // 秘钥
          // 角色权限，超级管理员返还空
          "auth": [
            {
                "menuName": "系统用户", // 菜单名
                "menuId": "640050a9c3b1371d9071e93e" // 菜单ID
                "authKey": "SYS_USER", // 权限标识（前端根据此标识显示或隐藏功能）
            }
          ]
        }
    }
   */
  async login() {
    const { ctx } = this
    const { body } = ctx.request

    const loginResult = await ctx.service.systemUser.login({
      username: body.username,
      password: body.password,
    })

    if (ctx.session)
      ctx.session.admin = {
        ...loginResult.user,
      }

    ctx.body = {
      code: 0,
      msg: '登录成功',
      data: {
        user: loginResult.user,
        token: loginResult.token,
        expireTime: loginResult.expireTime,
      },
    }
  }

  // 刷新Token
  async refreshToken() {
    const { ctx } = this
    const { admin } = ctx.state

    const loginResult = await ctx.service.systemUser.login(null, {
      _id: admin.id || admin.adminId,
    })

    if (ctx.session) ctx.session.admin = loginResult

    ctx.state = {
      code: 0,
      msg: 'success',
      data: {
        username: loginResult.username,
        isAdmin: loginResult.isAdmin,
        token: loginResult.token,
        auth: loginResult.auth,
      },
    }
  }
}

module.exports = AdminController
